package com.itheima.health.config;


import com.itheima.health.filter.JWTAuthenticationFilter;
import com.itheima.health.filter.JWTAuthorizationFilter;
import com.itheima.health.filter.JwtProperties;
import com.itheima.health.userdetailservice.MyUserDetailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

/**
 * EnableGlobalMethodSecurity 开启spring security 注解支持
 * EnableConfigurationProperties 扫描有 这个ConfigurationProperties 注解的类 把它扔到容器里
 */

@EnableConfigurationProperties(JwtProperties.class)
@EnableGlobalMethodSecurity(prePostEnabled = true)
@Configuration
public class MyConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private MyUserDetailService myUserDetailService;

    @Autowired
    private JwtProperties jwtProperties;

    @Bean
    public BCryptPasswordEncoder passwordEncoder() {
        //  密码加密 对象
        return new BCryptPasswordEncoder();
    }

//     过滤器忽略的静态资源
//    @Override
//    public void configure(WebSecurity web) throws Exception {
//        web.ignoring().antMatchers("/css/*","/js/*","/login.html");
//    }


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf()
                .disable()
                .addFilter(new JWTAuthenticationFilter(super.authenticationManager(),jwtProperties))
                .addFilter(new JWTAuthorizationFilter(super.authenticationManager(),jwtProperties))
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    }

    /**
     * 认证管理器对象
     * 数据库版用户认证
     * @param auth
     * @throws Exception
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(myUserDetailService).passwordEncoder(passwordEncoder());
    }
}
